package com.pig.graduate.common.security;


import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.pig.graduate.domain.sys.SysLog;
import com.pig.graduate.domain.sys.SysMenu;
import com.pig.graduate.domain.sys.SysRole;
import com.pig.graduate.domain.sys.SysUser;
import com.pig.graduate.result.MyResult;
import com.pig.graduate.service.sys.SysLogService;
import com.pig.graduate.service.sys.SysMenuService;
import com.pig.graduate.service.sys.SysRoleService;
import com.pig.graduate.service.sys.SysUserService;
import com.pig.graduate.util.IpUtil;
import com.pig.graduate.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 登录成功的处理
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysLogService sysLogService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        String username=authentication.getName(); // 获取用户名
        sysUserService.update(new UpdateWrapper<SysUser>().set("login_date",new Date()).eq("username",username)); // 更新最后登录日期

        // 生成jwt token
        String token=JwtUtils.getJwtToken(username);

        SysUser currentUser = sysUserService.getUserByUsername(username);


        // 获取当前用户拥有的权限菜单
        // 获取角色
        List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id=" + currentUser.getId()));

        // 设置角色
        currentUser.setRoles(roleList.stream().map(SysRole::getName).collect(Collectors.joining(",")));

        StringBuffer permsStr=new StringBuffer();

        // 获取菜单权限
        Set<SysMenu> menuSet = new HashSet<SysMenu>();
        for(SysRole sysRole:roleList){
            List<SysMenu> sysMenuList = sysMenuService.list(new QueryWrapper<SysMenu>().inSql("id", "select menu_id from sys_role_menu where role_id=" + sysRole.getId()));
            for(SysMenu sysMenu:sysMenuList){
                menuSet.add(sysMenu);
                permsStr.append(sysMenu.getPerms()+",");
            }
        }

        String perms[]= StringUtils.tokenizeToStringArray(permsStr.toString(),",");

        List<SysMenu> sysMenuList = new ArrayList<>(menuSet); // 转成集合List

        sysMenuList.sort(Comparator.comparing(SysMenu::getOrderNum));  // 排序

        List<SysMenu> menuList = sysMenuService.buildTreeMenu(sysMenuList); // 构造菜单树

        outputStream.write(JSONUtil.toJsonStr(MyResult.success("登录成功").put("authorization",token).put("menuList",menuList).put("currentUser",currentUser).put("perms",perms)).getBytes("UTF-8"));
        try{
            SysLog sysLog = new SysLog();
            sysLog.setUserId(currentUser.getId());
            String ip = IpUtil.getIpAddr(httpServletRequest);
            sysLog.setIp("0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip);
            UserAgent userAgent = UserAgentUtil.parse(httpServletRequest.getHeader("user-agent"));
            sysLog.setBrowser(
                    "Unknown".equals(userAgent.getBrowser().toString()) ? "未知" : userAgent.getBrowser().toString() );
            sysLog.setOperate(currentUser.getUsername()+"登录");
            sysLog.setRequestTime(System.currentTimeMillis()-start + "ms");
            sysLog.setIpAddress(
                    "内网IP内网IP".equals(IpUtil.getIpPossession(ip)) ? "本机" : IpUtil.getIpPossession(ip));
            sysLog.setCreateTime(new Date());
            sysLogService.save(sysLog);
        }catch (Exception e){
            e.printStackTrace();
        }
        outputStream.flush();
        outputStream.close();
    }


}
